import React, {
  Component,
  useState,
  useEffect,
} from "react";
import {
  View,
  FlatList,
  Text,
  Image,
} from "react-native";
import Content from "../../components/content/content";
import TaskComponent from "../../components/task/task";
import FooterLoading from "../../components/footer-loading/footer-loading";
import styles from "./order-sheet";

import * as api from "../../api";
import * as config from "../../config";

import * as statusBarSetting from '../../model/statusBarSetting';

export default function Order(props) {
  const [data, setData] = useState([]);
  const [refresh, setRefresh] = useState(false);
  const [page, setPage] = useState(1);
  const [allPage, setAllPage] = useState(1);
  const [showEmpty, setShowEmpty] = useState(false);
  const [footerText, setFooterText] = useState(false);

  const getTask = (data = []) => {
    setRefresh(true);
    api.getTasks({
      page,
      page_size: config.PAGE_SIZE,
    }).then(res => {
      const allPage = Math.ceil(res.pagination.count / config.PAGE_SIZE);
      const result = [...data, ...res.tasks];
      setAllPage(allPage);
      setData(result);
      setEmptyComponent(result);
      setFooter(allPage);
    }).catch(rej => {
      global.showToast(rej);
    }).finally(() => {
      setRefresh(false);
    });
  };

  setEmptyComponent = (result) => {
    setShowEmpty(result.length > 0 ? false : true);
  };

  setFooter = (result) => {
    setFooterText(page >= result);
  };

  statusBarSetting.useSetBackground(props);

  useEffect(() => {
    if (page === 0) {
      return;
    }
    if (page === 1) {
      getTask();
    } else {
      getTask(data);
    }
  }, [page]);

  onEndReached = () => {
    if (data.length < config.PAGE_SIZE) {
      return;
    }

    if (page >= allPage) {
      return;
    }

    setPage(page + 1);
  };

  onRefresh = () => {
    setPage(0);
    setTimeout(() => {
      setPage(1);
    });
  };

  footer = () => {
    if (page <= 1) {
      return;
    }
    return <FooterLoading showLoading={footerText} />
  };

  Empty = () => {
    return (
      showEmpty ? <Text style={{textAlign: "center",marginTop:50}}>暂无数据</Text> : null
    );
  };

  return (
    <Content>
      <View style={styles.content}>
        <FlatList 
          style={styles.listContent}
          data={data}
          refreshing={refresh}
          onRefresh={this.onRefresh}
          onEndReachedThreshold={0.2}
          onEndReached={this.onEndReached}
          scrollEventThrottle={500}
          renderItem={({item, index})=><TaskComponent key={index} {...item} router='Detail' />}
          ListEmptyComponent={this.Empty()}
          ListFooterComponent={this.footer()}
          keyExtractor={(item,index)=>index.toString()}
          progressViewOffset={20}
          getItemLayout={(data, index) => (
            {length: 100, offset: 100 * index, index}
          )}
        />
      </View>
    </Content>
  )
}